<template>
  <div class="edit-dialog">
    <el-dialog
      v-model="dialog"
      :title="titleName"
      :visible.sync="dialog"
      :close-on-click-modal="false"
      :show-close="false"
      width="700px"
      center
    >
      <el-form :model="addFormData" :rules="rules" ref="formRef" label-width="auto">
        <el-row :gutter="5">
          <el-col :span="6" class="col">
            <div class="grid-content bg-purple">参数</div>
          </el-col>
          <el-col :span="6" class="col">
            <div class="grid-content bg-purple">公式</div>
          </el-col>
          <el-col :span="6" class="col">
            <div class="grid-content bg-purple">a</div>
          </el-col>
          <el-col :span="6" class="col">
            <div class="grid-content bg-purple">b</div>
          </el-col>
        </el-row>
        <el-row :gutter="5" v-if="showTemperature">
          <el-col :span="6" class="col">
            <div class="grid-content">温度(℃)</div>
          </el-col>
          <el-col :span="6" class="col">
            <div class="grid-content"></div>
          </el-col>
          <el-col :span="6" class="col">
            <el-input-number v-model="addFormData.opt_temperature_a" :precision="1" :step="0.1" :min="0" :max="10"
                             class="input"></el-input-number>
          </el-col>
          <el-col :span="6" class="col">
            <el-input-number v-model="addFormData.opt_temperature_b" :precision="1" :step="1" :min="-1024" :max="1024"
                             class="input"></el-input-number>
          </el-col>
        </el-row>
        <el-row :gutter="5" v-if="showHumility">
          <el-col :span="6" class="col">
            <div class="grid-content">湿度(%)</div>
          </el-col>
          <el-col :span="6" class="col">
            <div class="grid-content"></div>
          </el-col>
          <el-col :span="6" class="col">
            <el-input-number v-model="addFormData.opt_humility_a" :precision="1" :step="0.1" :min="0" :max="10"
                             class="input"></el-input-number>
          </el-col>
          <el-col :span="6" class="col">
            <el-input-number v-model="addFormData.opt_humility_b" :precision="1" :step="1" :min="-1024" :max="1024"
                             class="input"></el-input-number>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="6" class="col">
            <div class="grid-content">照度(lx)</div>
          </el-col>
          <el-col :span="6" class="col">
            <div class="grid-content"></div>
          </el-col>
          <el-col :span="6" class="col">
            <el-input-number v-model="addFormData.cor_opt_lux_a" :precision="1" :step="0.1" :min="0" :max="10"
                             class="input"></el-input-number>
          </el-col>
          <el-col :span="6" class="col">
            <el-input-number v-model="addFormData.cor_opt_lux_b" :precision="1" :step="1" :min="-1024" :max="1024"
                             class="input"></el-input-number>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="6" class="col">
            <div class="grid-content">色温(K)</div>
          </el-col>
          <el-col :span="6" class="col">
            <div class="grid-content"></div>
          </el-col>
          <el-col :span="6" class="col">
            <el-input-number v-model="addFormData.cct_a" :precision="1" :step="0.1" :min="0" :max="10"
                             class="input"></el-input-number>
          </el-col>
          <el-col :span="6" class="col">
            <el-input-number v-model="addFormData.cct_b" :precision="1" :step="1" :min="-1024" :max="1024"
                             class="input"></el-input-number>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="6" class="col">
            <div class="grid-content">EML</div>
          </el-col>
          <el-col :span="6" class="col">
            <div class="grid-content">y=ax+b</div>
          </el-col>
          <el-col :span="6" class="col">
            <el-input-number v-model="addFormData.eml_a" :precision="1" :step="0.1" :min="0" :max="10"
                             class="input"></el-input-number>
          </el-col>
          <el-col :span="6" class="col">
            <el-input-number v-model="addFormData.eml_b" :precision="1" :step="1" :min="-1024" :max="1024"
                             class="input"></el-input-number>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="6" class="col">
            <div class="grid-content">EDI(lx)</div>
          </el-col>
          <el-col :span="6" class="col">
            <div class="grid-content"></div>
          </el-col>
          <el-col :span="6" class="col">
            <el-input-number v-model="addFormData.edi_a" :precision="1" :step="0.1" :min="0" :max="10"
                             class="input"></el-input-number>
          </el-col>
          <el-col :span="6" class="col">
            <el-input-number v-model="addFormData.edi_b" :precision="1" :step="1" :min="-1024" :max="1024"
                             class="input"></el-input-number>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="6" class="col">
            <div class="grid-content">CL<sub>A</sub></div>
          </el-col>
          <el-col :span="6" class="col">
            <div class="grid-content"></div>
          </el-col>
          <el-col :span="6" class="col">
            <el-input-number v-model="addFormData.cla_a" :precision="1" :step="0.1" :min="0" :max="10"
                             class="input"></el-input-number>
          </el-col>
          <el-col :span="6" class="col">
            <el-input-number v-model="addFormData.cla_b" :precision="1" :step="1" :min="-1024" :max="1024"
                             class="input"></el-input-number>
          </el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="6" class="col">
            <div class="grid-content">CS</div>
          </el-col>
          <el-col :span="6" class="col">
            <div class="grid-content"></div>
          </el-col>
          <el-col :span="6" class="col">
            <el-input-number v-model="addFormData.cs_a" :precision="1" :step="0.1" :min="0" :max="10"
                             class="input"></el-input-number>
          </el-col>
          <el-col :span="6" class="col">
            <el-input-number v-model="addFormData.cs_b" :precision="1" :step="1" :min="-1024" :max="1024"
                             class="input"></el-input-number>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div label="" class="grid-content bg-purple-light">注：参数a默认1，参数b默认为0</div>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" :loading="submitLoading" icon="el-icon-check"
                     @click="submit('formRef')">确 认</el-button>
          <el-button icon="el-icon-close" @click="handleClose">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import {deviceAdjustInfo, deviceAdjust} from '@/api/deviceManage'

  export default {
    name: "adjustForm",
    props: {
      formData: Object,
      showTemperature: Boolean,
      showHumility: Boolean,
      showDialog: Boolean
    },
    data() {
      return {
        addFormData: {
          deviceId: "",
          opt_temperature_a: 1,
          opt_temperature_b: 0,
          opt_humility_a: 1,
          opt_humility_b: 0,
          cor_opt_lux_a: 1,
          cor_opt_lux_b: 0,
          cct_a: 1,
          cct_b: 0,
          eml_a: 1,
          eml_b: 0,
          edi_a: 1,
          edi_b: 0,
          cla_a: 1,
          cla_b: 0,
          cs_a: 1,
          cs_b: 0
        },
        titleName: "设备参数校准",
        submitLoading: false,
        rules: {
          opt_temperature_a: [{required: true, message: "请输入0-10之间的数字", trigger: "blur"}],
          opt_temperature_b: [{required: true, message: "请输入-1024到1024之间的数字", trigger: "blur"}],
        }
      };
    },
    mounted() {
      this.addFormData.deviceId = this.$route.query.deviceId;
      //console.log("deviceId=" + this.addFormData.deviceId);
      deviceAdjustInfo(this.addFormData.deviceId).then(response => {
        //console.log("接收到的数据:", response .value);
        if (response && response.value) {
          this.parseDataToForm(response.value);
        }
      });
    },
    computed: {
      dialog: function () {
        return this.showDialog;
      },
    },
    watch: {
      // 当 showDialog 改变为 true 时，加载数据
      async showDialog(newVal) {
        if (newVal) {
          // 如果 deviceId 还没设置，可以从 props 或其他方式获取
          if (!this.addFormData.deviceId) {
            this.addFormData.deviceId = this.$route.query.deviceId;
          }
          await this.loadData(); // 调用加载数据的方法
        }
      }
    },
    methods: {
      // 取消事件
      handleClose() {
        this.$emit("adjustVisible", false);
      },
      // 解析 value 数组并赋值给表单
      parseDataToForm(dataArray) {
        dataArray.forEach(item => {
          const typeMap = {
            OPT_TEMPERATURE: 'opt_temperature',
            OPT_HUMILITY: 'opt_humility',
            COR_OPT_LUX: 'cor_opt_lux',
            CCT: 'cct',
            EML: 'eml',
            EDI: 'edi',
            CLA: 'cla',
            CS: 'cs'
          };
          const fieldName = typeMap[item.type];
          if (fieldName) {
            this.addFormData[`${fieldName}_a`] = item.a;
            this.addFormData[`${fieldName}_b`] = item.b;
          }
        });
      },
      async loadData() {
        try {
          const response = await deviceAdjustInfo(this.addFormData.deviceId);
          if (response && response.value) {
            this.parseDataToForm(response.value);
          }
        } catch (error) {
          console.error('加载设备校准信息失败:', error);
        }
      },
      submit(formName) {
        this.submitLoading = true;
        this.$refs[formName].validate(valid => {
          if (valid) {
            const that = this;
            // 创建要发送的数据对象
            let sendData = {
              deviceId: this.addFormData.deviceId,
              factors: []
            };

            // 定义类型映射
            const typeMap = [
              {key: 'opt_temperature', type: 'OPT_TEMPERATURE'},
              {key: 'opt_humility', type: 'OPT_HUMILITY'},
              {key: 'cor_opt_lux', type: 'COR_OPT_LUX'},
              {key: 'cct', type: 'CCT'},
              {key: 'eml', type: 'EML'},
              {key: 'edi', type: 'EDI'},
              {key: 'cla', type: 'CLA'},
              {key: 'cs', type: 'CS'}
            ];

            // 填充factors数组
            typeMap.forEach(item => {
              sendData.factors.push({
                type: item.type,
                a: this.addFormData[`${item.key}_a`],
                b: this.addFormData[`${item.key}_b`]
              });
            });

            //console.log('准备发送的数据:', JSON.stringify(sendData));

            deviceAdjust(sendData)
              .then(res => {
                that.submitLoading = false;
                if (res['code'] == 200) {
                  that.$emit("adjustVisible", false);
                  that.$emit("initData");
                  that.$message.success('校准成功!')
                } else {
                  that.$message(res['msg'])
                }
              })
              .catch(() => {
                that.submitLoading = false
              })
          } else {
            this.submitLoading = false;
            return false;
          }
        });
      }
    },
  };
</script>

<style>
  .col {
    border-radius: 4px;
    height: 40px;
  }

  .input {
    width: auto; /* 让输入框宽度占满父容器 */
    box-sizing: border-box; /* 确保 padding 和 border 不会增加额外的宽度 */
  }

  .bg-purple-light {
    height: 36px;
    text-align: center;
    line-height: 36px;
    color: #ff8b5b;
    background: #d3dce6;
  }

  .bg-purple {
    background: #d3dce6;
  }

  .grid-content {
    font-weight: bold;
    text-align: center;
    line-height: 36px;
    border-radius: 4px;
    min-height: 36px;
  }
</style>
